package org.xu.upms.server.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.xu.upms.server.dao.AppDao;
import org.xu.upms.server.dao.UserDao;
import org.xu.upms.server.model.User;
import org.xu.upms.server.service.UserService;

import com.xu.commons.enums.TrueFalseEnum;
import com.xu.commons.model.Result;
import com.xu.commons.model.ResultCode;
@Service("userService")
public class UserServiceImpl implements UserService{
	
	@Autowired
	private UserDao userDao;
	@Autowired
	private AppDao appDao;
	@Override
	public Result Login(String ip, String appCode, String account, String password) {
		//查询数据库是否有改用户
		Result result = Result.createSuccessResult();
		User user = findByAccount(account);
		if (user == null) {
			result.setCode(ResultCode.ERROR).setMessage("登录名不存在");
		}
		else if (!user.getPassword().equals(password)) {
			result.setCode(ResultCode.ERROR).setMessage("密码不正确");
		}
		else if (!user.getIsEnable()) {
			result.setCode(ResultCode.ERROR).setMessage("已被管理员禁用");
		}
		
		//用户id的查询已分配的应用
		List<String> appsCodes=appDao.findAppCodeByUserId(TrueFalseEnum.TRUE.getValue(), user.getId());
		if(CollectionUtils.isEmpty(appsCodes)){
			result.setCode(ResultCode.ERROR).setMessage("不存在可操作应用");
		}else if(!appsCodes.contains(appCode)){
			result.setCode(ResultCode.ERROR).setMessage("没有应用操作权限");
		}else {
			user.setLastLoginIp(ip);
			user.setLoginCount(user.getLoginCount() + 1);
			user.setLastLoginTime(new Date().getTime()/1000);
			userDao.update(user);
			//dao.update(user);
			result.setData(user);
		}
		return result;
	}

	@Override
	public User findByAccount(String account) {
		
		return userDao.findByAccount(account);
	}

}
